const { query } = require('../config/db');

async function debugQuery() {
  try {
    console.log('🔍 调试数据库查询...');

    // 1. 检查messages表结构
    console.log('\n📋 检查messages表结构:');
    const tableStructure = await query('DESCRIBE messages');
    tableStructure.forEach(column => {
      console.log(`   ${column.Field}: ${column.Type} (${column.Null === 'YES' ? 'NULL' : 'NOT NULL'})`);
    });

    // 2. 检查数据
    console.log('\n📊 检查messages表数据:');
    const messages = await query('SELECT id, group_id, sender_id, message_type, LEFT(content, 50) as content_preview FROM messages LIMIT 5');
    messages.forEach(msg => {
      console.log(`   ID: ${msg.id}, GroupID: ${msg.group_id} (${typeof msg.group_id}), SenderID: ${msg.sender_id}, Type: ${msg.message_type}`);
    });

    // 3. 测试简单查询
    console.log('\n🧪 测试简单查询:');
    const simpleQuery = await query('SELECT COUNT(*) as count FROM messages WHERE group_id = ?', [1]);
    console.log(`   群组1的消息数量: ${simpleQuery[0].count}`);

    // 4. 测试带JOIN的查询
    console.log('\n🧪 测试带JOIN的查询:');
    const joinQuery = await query(`
      SELECT m.id, m.content, u.nickname 
      FROM messages m 
      LEFT JOIN users u ON m.sender_id = u.id 
      WHERE m.group_id = ? 
      LIMIT 3
    `, [1]);
    
    joinQuery.forEach(msg => {
      console.log(`   消息ID: ${msg.id}, 发送者: ${msg.nickname || '未知'}, 内容: ${msg.content.substring(0, 30)}...`);
    });

    // 5. 测试分页查询
    console.log('\n🧪 测试分页查询:');
    const pageQuery = await query(`
      SELECT m.id, m.content 
      FROM messages m 
      WHERE m.group_id = ? 
      ORDER BY m.created_at DESC 
      LIMIT ? OFFSET ?
    `, [1, 5, 0]);
    
    console.log(`   分页查询结果数量: ${pageQuery.length}`);

  } catch (error) {
    console.error('❌ 调试查询失败:', error);
  }
}

debugQuery();
